#include "TanContainer.h"
#include <core/Tan.h>

namespace qtangram {
TanContainer::TanContainer()
{
}

void TanContainer::allTansCoordsTo(const ContainerWidget* widget)
{
    for(auto ti=tans.begin(); ti!=tans.end(); ++ti)
        (*ti)->polyScreen = CoordinateTransformer::worldToScreen(widget,(*ti)->polyCurrent);
}

void TanContainer::deselectAllTans()
{
    QLinkedList<Tan*>::iterator ti;
    for(ti=selection.begin(); ti!=selection.end(); ++ti) (*ti)->selected=false;
    selection.clear();
}

void TanContainer::selectTan(Tan *t)
{
    if (!t->selected)
    {
        selection.push_back(t);
        t->selected=true;
    }
}

int TanContainer::selectTanAt(QPointF p)
{
    QLinkedList<Tan*>::iterator it;
    bool found=false;

    for(it=tans.begin(); it!=tans.end() && !found; ++it)
    {

        if((*it)->getCurrentPoly().containsPoint(p,Qt::OddEvenFill) )
        {
            selectTan(*it);
            found=true;
        }
    }
    return selection.count();
}

int TanContainer::selectTanAt(QPointF a, QPointF b)
{
    if (a==b) return selectTanAt(a);
    QLinkedList<Tan*>::iterator it;

    QPolygonF poly;

    qreal tmp;
    if (a.x() > b.x())
    { tmp=a.x(); a.setX(b.x()); b.setX(tmp); }
    if (a.y() > b.y())
    { tmp=a.y(); a.setY(b.y()); b.setY(tmp); }
    poly << a << QPointF(b.x(),a.y()) << b << QPointF(a.x(),b.y());

    for(it=tans.begin(); it!=tans.end(); ++it)
    {
        if(poly.containsPoint((*it)->currentPoint,Qt::OddEvenFill))
        {
            selectTan(*it);
        }
    }
    return selection.count();
}

Tan* TanContainer::findTanAt(QPointF p)
{
    QLinkedList<Tan*>::iterator it;
    Tan* res=NULL;
    for(it=tans.begin(); it!=tans.end() && !res; ++it)
    {
        if((*it)->getCurrentPoly().containsPoint(p,Qt::OddEvenFill) )  res = (*it);
    }
    return res;
}

bool TanContainer::isSelected(Tan *t)
{
    for (auto it=selection.begin(); it!=selection.end(); ++it)
    {
        if ((*it)==t) return true;
    }
    return false;
}
}
